package cn.flashapp.queue;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import cn.flashapp.queue.reponsitory.NotificationQueue;
import cn.flashapp.queue.threadpool.ThreadPoolManager;
import cn.flashapp.queue.util.DealNotifyOtherQueue;
import cn.flashapp.queue.util.DealNotifyTopQueue;

public class Server extends Thread {
	private static Logger logger = Logger.getLogger(Server.class);

	private static ThreadPoolManager manager = ThreadPoolManager.getInstance(0, 30, 5, 1000);;

	private List<String> list = null;

	public Server(List<String> x) {
		this.list = x;
	}

	@Override
	public void run() {
		try {
			System.out.println("Server.run(): 启动Server线程: " + this.getId());
			logger.info("Server.run(): 启动Server线程: " + this.getId());
			while (true) {
				// 循环获取队列中内容
				if (list != null && (!list.isEmpty())) {
					for (String str : list) {
						try {
							NotificationQueue instance = NotificationQueue.getInstance();
							instance.setCname(str);
							String msg = instance.popTopMsgFromQueue();
							if ( !StringUtils.isBlank( msg ) ) {
								// 获取到消息 ,启动处理线程
								logger.info( "获取到队列消息 ,启动处理线程=" + msg );
								System.out.println( instance.getCname() + "获取到队列消息 ,启动处理线程=" + msg );
								manager.execute( new DealNotifyTopQueue( msg ) );
							}
							
							msg = instance.popOtherMsgFromQueue();
							if ( !StringUtils.isBlank( msg ) ) {
								logger.info( "获取到队列消息 ,启动处理线程=" + msg );
								System.out.println( instance.getCname() + "获取到队列消息 ,启动处理线程=" + msg );
								manager.execute( new DealNotifyOtherQueue( msg ) );
							}
						} catch (Exception ex) {
							try {
								Thread.sleep(100);
							} catch (Exception e) {
								logger.error(e);
							}
							continue;
						}
					}
				}
				try {
					Thread.sleep(100);
				} catch (Exception ex) {
					logger.error(ex);
				}
			}
		} catch (Exception e) {
			logger.error(e);
		}
	}

	public static void main(String[] args) {
		
	}
}